package cn.emailChat.ai.repo;

import cn.emailChat.ai.domain.ConversationSummary;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * @Description 对话摘要表的持久化、查询、删除等操作
 * @Author susu
 * @Date 2025/8/20
 */
public interface ConversationSummaryRepo extends JpaRepository<ConversationSummary, String> {
    List<ConversationSummary> findByContactEmailAndStatusOrderByUpdatedAtDesc(String contactEmail, String status);
    Optional<ConversationSummary> findTop1ByContactEmailOrderByUpdatedAtDesc(String contactEmail);

    // A. 定时“可蒸馏”的开放线程（最近活跃 + 距离上次同步已过最小间隔）
    @Query("""
      select cs from ConversationSummary cs
       where cs.status = 'open'
         and cs.updatedAt >= :activeSince
         and (cs.lastProfileSyncAt is null or cs.lastProfileSyncAt < :resyncBefore)
       order by cs.updatedAt desc
    """)
    List<ConversationSummary> findDistillCandidates(
            @Param("activeSince") LocalDateTime activeSince,
            @Param("resyncBefore") LocalDateTime resyncBefore,
            Pageable pageable);

    // B. 自动关闭候选：长时间未更新的开放线程
    @Query("""
      select cs from ConversationSummary cs
       where cs.status = 'open'
         and cs.updatedAt < :staleBefore
       order by cs.updatedAt asc
    """)
    List<ConversationSummary> findStaleOpenThreads(
            @Param("staleBefore") LocalDateTime staleBefore,
            Pageable pageable);
}
